/**
 * 此指令试用时候必须紧挨着input标签。中间不能有间隔。并且不能被包裹在label标签中（会获取不到焦点）。
 * <input class="padding-left-right-10  inline" ng-model="data.value" type="tel" maxlength="11"/>
 * <input-clear ng-model="data.value"></input-clear>
 * created by ZCP
 */
APP.directive('inputClear', ['$rootScope', '$state', '$ionicScrollDelegate', '$timeout',
  function ($rootScope, $state, $ionicScrollDelegate, $timeout) {
    return {
      restrict: 'E',
      replace: true,
      scope: {},
      require: 'ngModel',
      template: '<i class="icon ion-close-circled" ng-show="isShow" style="vertical-align: middle;color: #660000;position: relative;right: 25px;margin-left: -4px;display: inline-block;width: 0"></i>',
      link: function (scope, element, attr, controller) {
        scope.isShow = false;//控制显示X的标志位
        var input = element[0].previousElementSibling;

        scope.$on('$ionicView.beforeLeave', function () {
          scope.alive = false;
        });
        scope.$on('$ionicView.beforeEnter', function () {
          scope.alive = true;
        });

        input.onblur = function () {
          console.log('onblur');
          if (!scope.alive) {
            return;
          }
          scope.$apply(function () {
            scope.isShow = false;
          });
        };
        //输入框内有值,显示清空按钮
        input.onfocus = function () {
          scope.$apply(function () {
            if (input.value) {
              scope.isShow = true;
            }
          });
        };

        scope.$watch(function () {
          return input.value;
        }, function () {
          scope.isShow = !!input.value;
        });
        //如果清空按钮被点击了,就清空输入内容,并隐藏清空按钮
        element.on('click', function (event) {
          console.log('click');
          element[0].focus();
          controller.$setViewValue('');
          scope.isShow = false;

          var temp = input.blur;
          input.blur = function () {
            console.log('blur is overwrited!!');
          };

          $timeout(function () {
            input.blur = temp;
          }, 100);
        });

      }
    }
  }]);
